<template>
  <div class="scaner" ref="scaner">
    <div class="banner" v-if="showBanner">
      <i class="close_icon" @click="() => (showBanner = false)"></i>
      <p class="text">若当前浏览器无法扫码，请切换其他浏览器尝试</p>
    </div>
    <div class="cover">
      <p class="line"></p>
      <span class="square top left"></span>
      <span class="square top right"></span>
      <span class="square bottom right"></span>
      <span class="square bottom left"></span>
      <p class="tips">将二维码放入框内，即可自动扫描</p>
    </div>
    <video
      class="source"
      ref="video"
      id="video"
      :width="videoWH.width"
      :height="videoWH.height"
      :controls="true"
      autoplay
    ></video>
    <canvas id="canvas"  :width="videoWH.width"
      :height="videoWH.height" ref="canvas" />
  </div>
</template>
<script>
import jsQR from "jsqr";
import { userStore } from "../../stores/user.ts";
import { ElMessageBox, ElMessage } from "element-plus";
export default {
  name: "Scaner",
  props: {
    // 使用后置相机
    useBackCamera: {
      type: Boolean,
      default: true,
    },
    // 扫描识别后停止
    stopOnScaned: {
      type: Boolean,
      default: true,
    },
    drawOnfound: {
      type: Boolean,
      default: true,
    },
    // 线条颜色
    lineColor: {
      type: String,
      default: "red",
    },
    // 线条宽度
    lineWidth: {
      type: Number,
      default: 2,
    },
    // 视频宽度
    videoWidth: {
      type: Number,
      default: window.innerWidth,
    },
    // 视频高度
    videoHeight: {
      type: Number,
      default: window.innerHeight,
    },
    responsive: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      showPlay: false,
      showBanner: true,
      opacity:0,
      User_Code:null,
      Interface_Code:null,
       user:null ,
       t1:null,
       t2:null, 
       t3:null,
       t4:null,
       ts4:null
    };
  },
  computed: {
    videoWH() {
      return { width: this.videoWidth * 0.7, height: this.videoHeight };
    },
  },
  created(){
    this.user = userStore();
    this.User_Code = JSON.parse(sessionStorage.getItem("UserInfo")).sUser_Code;
    this.Interface_Code = sessionStorage.getItem("item");
  },
  methods: {
    // 画线
    drawLine(begin, end) {
      this.canvas.beginPath();
      this.canvas.moveTo(begin.x, begin.y);
      this.canvas.lineTo(end.x, end.y);
      this.canvas.lineWidth = this.lineWidth;
      this.canvas.strokeStyle = this.lineColor;
      this.canvas.stroke();
    },
    // 画框
    drawBox(location) {
      if (this.drawOnfound) {
        this.drawLine(location.topLeftCorner, location.topRightCorner);
        this.drawLine(location.topRightCorner, location.bottomRightCorner);
        this.drawLine(location.bottomRightCorner, location.bottomLeftCorner);
        this.drawLine(location.bottomLeftCorner, location.topLeftCorner);
      }
    },
    tick() {
      if (
        this.$refs.video &&
        this.$refs.video.readyState === this.$refs.video.HAVE_ENOUGH_DATA
      ) {
        this.$refs.canvas.height = this.videoWH.height;
        this.$refs.canvas.width = this.videoWH.width;
        this.canvas.drawImage(
          this.$refs.video,
          0,
          0,
          this.$refs.canvas.width,
          this.$refs.canvas.height
        );
        const imageData = this.canvas.getImageData(
          0,
          0,
          this.$refs.canvas.width,
          this.$refs.canvas.height
        );
        let code = false;
        try {
          code = jsQR(imageData.data, imageData.width, imageData.height);
        } catch (e) {
          console.error(e);
        }
        if (code) {
      this.drawBox(code.location);
      this.found(code.data);
      console.log("code", code)
      var keyValue =code.data.split("&");
      console.log(keyValue);
      var obj = {};
      for (var i = 0; i < keyValue.length; i++) {
        //循环分割挂过后的地址
        var item = keyValue[i].split("=");
        var key = item[0];
        var value = item[1];
        obj[key] = value;
      }
      console.log("nnm", obj.Check_No);
      this.user.xqlist1 = obj;
      sessionStorage.setItem("xq1", JSON.stringify(obj)); // location.reload()
      axios
        .post(
          window.globalUrl.server + "Service.asmx/Get_CheckSub_Data",
          JSON.stringify({
            User_Code: this.User_Code,
            Interface_Code: this.Interface_Code,
            Check_No: obj.Check_No,
          })
        )
        .then((res) => {
          console.log(res);
          if (res.data.RltCode == 1) {
            this.user.Get_CheckSub_Data = JSON.parse(res.data.RltData);
            sessionStorage.setItem(
              "data",
              JSON.stringify(JSON.parse(res.data.RltData))
            );
            sessionStorage.removeItem("t1");
            sessionStorage.removeItem("t2");
            sessionStorage.removeItem("t3");
            sessionStorage.removeItem("t4");
            sessionStorage.removeItem("ts4");
            this.user.tableData1 = [];
            this.user.tableData2 = [];
            this.user.tableData3 = [];
            this.user.tableData4 = [];
            this.user.tableDatas4 = [];
            axios
              .post(
                window.globalUrl.server + "Service.asmx/GetQueInHoss",
                JSON.stringify({
                  User_Code: this.User_Code,
                  Interface_Code: this.Interface_Code,
                  Pson_CardID: this.user.xqlist1.Pson_CardID,
                })
              )
              .then((res) => {
                if (res.data.RltCode == 1) {
                  console.log("立棍", JSON.parse(res.data.RltData));
                 this.t1 = JSON.parse(res.data.RltData);
                 this.t1= this.t1.map((item) => ({
                    date1: item["Hos_InDate"],
                    date2: item["Hos_OutDate"],
                    date3: item["Hos_Cause"],
                    date4: item["Hos_Group"],
                    date5: item["Hos_No"],
                  }));
                  this.user.tableData1 =this.t1;
                  sessionStorage.setItem("t1", JSON.stringify(this.t1));
                }
              });

            axios
              .post(
                window.globalUrl.server + "Service.asmx/GetQueHomeHoss",
                JSON.stringify({
                  User_Code: this.User_Code,
                  Interface_Code: this.Interface_Code,
                  Pson_CardID: this.user.xqlist1.Pson_CardID,
                })
              )
              .then((res) => {
                if (res.data.RltCode == 1) {
                  console.log("立棍", JSON.parse(res.data.RltData));
                  this.t2 = JSON.parse(res.data.RltData);
                 this.t2 = this.t2.map((item) => ({
                    date1: item["Hos_InDate"],
                    date2: item["Hos_OutDate"],
                    date3: item["Hos_Cause"],
                    date4: item["Hos_Group"],
                    date5: item["Hos_No"],
                  }));
                  this.user.tableData2 =this.t2;
                  sessionStorage.setItem("t2", JSON.stringify(this.t2));
                }
              });

            axios
              .post(
                window.globalUrl.server + "Service.asmx/GetQueInoculs",
                JSON.stringify({
                  User_Code: this.User_Code,
                  Interface_Code: this.Interface_Code,
                  Pson_CardID: this.user.xqlist1.Pson_CardID,
                })
              )
              .then((res) => {
                if (res.data.RltCode == 1) {
                  console.log("立棍", JSON.parse(res.data.RltData));
                  this.t3 = JSON.parse(res.data.RltData);
                  this.t3 = this.t3.map((item) => ({
                    name: item["Ino_Name"],
                    date1: item["Ino_Date"],
                    date2: item["Ino_Group"],
                  }));
                 this.user.tableData3 = this.t3;
                  sessionStorage.setItem("t3", JSON.stringify(this.t3));
                }
              });
            axios
              .post(
                window.globalUrl.server + "Service.asmx/GetQueUseMedis",
                JSON.stringify({
                  User_Code: this.User_Code,
                  Interface_Code: this.Interface_Code,
                  Check_No: this.user.xqlist1.Check_No,
                })
              )
              .then((res) => {
                if (res.data.RltCode == 1) {
                  console.log("立棍", JSON.parse(res.data.RltData));
                  this.ts4 = JSON.parse(res.data.RltData);
                  this.user.tableDatas4 = this.ts4.map((item) => ({
                    name: item["Medi_Name"],
                    date1: item["Medi_UseName"],
                    date1_id: item["Medi_Use"],
                    date2: item["Medi_freqName"],
                    date2_id: item["Medi_freq"],
                    date3: item["Medi_EachDose"],
                    date4: item["Medi_EachDoseUnit"],
                    date5: item["Medi_DoseUnitName"],
                    date5_id: item["Medi_DoseUnit"],
                    date6: item["Medi_UseDate"],
                    date7: item["Medi_UseDateUnitName"],
                    date7_id: item["Medi_UseDateUnit"],
                    date8: item["Medi_MedicineYieldName"],
                    date8_id: item["Medi_MedicineYield"],
                    // date9: item["Medi_Sugg"],
                    // date9_id: item["Medi_TypeID"],
                  }));
                  sessionStorage.setItem(
                    "ts4",
                    JSON.stringify(this.user.tableDatas4)
                  );
                 this.user.tableData4 = this.user.tableDatas4.map((item) => ({
                    name: item["name"],
                    date1: item["date1"],
                    date1_id: item["date1_id"],
                    date2:
                      item["date2"] +
                      item["date3"] +
                      "次；1次" +
                      item["date4"] +
                      item["date5"],
                    date2_id: item["date2_id"],
                    date3: item["date3"],
                    date4: item["date6"] + item["date7"],
                    dates4: item["date4"],
                    date5: item["date5"],
                    date5_id: item["date5_id"],
                    date6: item["date6"],
                    date7: item["date7"],
                    date7_id: item["date7"],
                    date8: item["date8"],
                    date8_id: item["date8_id"],
                    // date9: item["date9"],
                    // date9_id: item["date9_id"],
                  }));
                  sessionStorage.setItem("t4", JSON.stringify(this.user.tableData4));
                }
              });
              this.fullStop()
              this.$router.replace("/jkwd");
          } else {
            if (res.data.RltCode == 0) {
              ElMessage.error(res.data.RltMsg);
            }
            sessionStorage.removeItem("t1");
            sessionStorage.removeItem("t2");
            sessionStorage.removeItem("t3");
            sessionStorage.removeItem("t4");
            sessionStorage.removeItem("ts4");
            this.user.tableData1 = [];
            this.user.tableData2 = [];
            this.user.tableData3 = [];
            this.user.tableData4 = [];
            this.user.tableDatas4 = [];
              // this.$router.replace("/jkwd");
          }
        })
        .catch((eorro) => {
          sessionStorage.removeItem("t1");
          sessionStorage.removeItem("t2");
          sessionStorage.removeItem("t3");
          sessionStorage.removeItem("t4");
          sessionStorage.removeItem("ts4");
          this.user.tableData1 = [];
          this.user.tableData2 = [];
          this.user.tableData3 = [];
          this.user.tableData4 = [];
          this.user.tableDatas4 = [];
          //  this.$router.replace("/jkwd");
        });
        }
      }
      this.run();
    },
    // 初始化
    setup() {
      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        this.previousCode = null;
        this.parity = 0;
        this.canvas = this.$refs.canvas.getContext("2d");
        const facingMode = this.useBackCamera
          ? { exact: "environment" }
          : "user";
        const handleSuccess = (stream) => {
        this.$refs.video.srcObject = stream;
          const playPromise = this.$refs.video.play();
          playPromise.then(this.run);
          if (this.$refs.video.onfocus) {
        this.$refs.video.onfocus = () => {
          console.log('Camera focused');
        };
      }
        };
        navigator.mediaDevices
          .getUserMedia({
            video: {
              facingMode,
              width: 640,
              height: 480,
              frameRate: 30 ,
               focusMode: 'continuous',
              focusDistance: { exact: 3000 }
            },
          })
          .then(handleSuccess)
          .catch((error) => {
            this.$emit("error-captured", error);
          });
      }
    },
    run() {
      requestAnimationFrame(this.tick);
    },
    found(code) {
      if (this.previousCode !== code) {
      this.previousCode = code;
      this.parity = 0; // 重置计数器
    } else {
      this.parity += 1;
      if (this.parity >= 2) {
        this.parity = 0;
        this.$emit("code-scanned", code);
      }
    }
    },
    // 完全停止
    fullStop() {
      if (this.$refs.video && this.$refs.video.srcObject) {
        this.$refs.video.srcObject.getTracks().forEach((t) => t.stop());
      }
    }
  },
  mounted() {
    this.setup();
  },
  beforeDestroy() {
    this.fullStop();
  },
};
</script>

<style lang="css" scoped>
.scaner {
  position: fixed;
  width: 100%;
  height: 100%;
  height: -webkit-calc(100%);
  height: -moz-calc(100%);
  height: -ms-calc(100%);
  height: -o-calc(100%);
  height: calc(100%);
}
#canvas {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
  /* transform: translate(-50%,-50%); */
}
#video {
   top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  position: fixed;
}
.scaner .banner {
  width: 340px;
  position: absolute;
  top: 16px;
  left: 50%;
  margin-left: -170px;
  background: #fa74a2;
  border-radius: 8px;
  box-sizing: border-box;
  padding: 12px;
  opacity: 0.9;
  box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
}
.scaner .banner .text {
  padding: 0;
  margin: 0;
  color: #ffffff;
  font-size: 12px;
  text-align: justify;
  text-align-last: left;
}
.scaner .banner .close_icon {
  display: inline-block;
  height: 24px;
  width: 24px;
  background: url("../assets/close.png") no-repeat center;
  background-size: auto 100%;
  position: absolute;
  right: 8px;
  top: 8px;
}
.scaner .cover {
  height: 220px;
  width: 220px;
  position: absolute;
  top: 50%;
  left: 50%;
  -webkit-transform: translate(-50%, -50%);
  -moz-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  -o-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border: 0.5px solid #999999;
  z-index: 1111;
}
.scaner .cover .line {
  width: 200px;
  height: 1px;
  margin-left: 10px;
  background: #5f68e8;
  background: linear-gradient(
    to right,
    transparent,
    #5f68e8,
    #0165ff,
    #5f68e8,
    transparent
  );
  position: absolute;
  -webkit-animation: scan 1.75s infinite linear;
  -moz-animation: scan 1.75s infinite linear;
  -ms-animation: scan 1.75s infinite linear;
  -o-animation: scan 1.75s infinite linear;
  animation: scan 1.75s infinite linear;
  -webkit-animation-fill-mode: both;
  -moz-animation-fill-mode: both;
  -ms-animation-fill-mode: both;
  -o-animation-fill-mode: both;
  animation-fill-mode: both;
  border-radius: 1px;
}
.scaner .cover .square {
  display: inline-block;
  height: 20px;
  width: 20px;
  position: absolute;
}
.scaner .cover .square.top {
  top: 0;
  border-top: 1px solid #5f68e8;
}
.scaner .cover .square.left {
  left: 0;
  border-left: 1px solid #5f68e8;
}
.scaner .cover .square.bottom {
  bottom: 0;
  border-bottom: 1px solid #5f68e8;
}
.scaner .cover .square.right {
  right: 0;
  border-right: 1px solid #5f68e8;
}
.scaner .cover .tips {
  position: absolute;
  bottom: -48px;
  width: 100%;
  font-size: 14px;
  color: #ffffff;
  opacity: 0.8;
}
@-webkit-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-moz-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@-o-keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
@keyframes scan {
  0% {
    top: 0;
  }
  25% {
    top: 50px;
  }
  50% {
    top: 100px;
  }
  75% {
    top: 150px;
  }
  100% {
    top: 200px;
  }
}
</style>








